package com.macro.mall.portal.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.portal.dao.BillLadingMapper;
import com.macro.mall.portal.dao.UserIncomeMapper;
import com.macro.mall.portal.domain.*;
import com.macro.mall.portal.domain.vo.PageVo;
import com.macro.mall.portal.domain.vo.TotalVo;
import com.macro.mall.portal.dto.*;
import com.macro.mall.portal.service.*;
import com.macro.mall.portal.dao.UserMapper;
import com.macro.mall.portal.util.RedisTool;
import com.macro.mall.portal.util.ShareCodeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 用户表 服务实现类
 *
 * @author db
 * @since 2021-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private RedisTool redisTool;

    @Autowired
    private BillLadingMapper billLadingMapper;

    @Autowired
    private IPartnerTypeService partnerTypeService;

    @Autowired
    private IUserIncomeService userIncomeService;

    @Autowired
    private UserIncomeMapper userIncomeMapper;

    @Autowired
    private IDataTotalService dataTotalService;

    @Autowired
    private IUserRollService userRollService;

    @Autowired
    private ILoanPlanService loanPlanService;


    //注册
    @Override
    public void registered(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", user.getOpenId());
        User one = userMapper.selectOne(wrapper);
        //当用户不为空的时候,不注册
        if (one != null) {
            return;
        }
        User users = user.toBuilder().username("微信用户").build();
        userMapper.insert(users);
        User build = users.toBuilder().shareCode(ShareCodeUtils.createCode(users.getId())).build();
        userMapper.updateById(build);
    }

    //用户详情
    @Override
    public User userInfo(String openId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openId);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public VxUserDto userInfos( User vxUser) {
        QueryWrapper< User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", vxUser.getOpenId());
         User user = this.getOne(wrapper);
        VxUserDto dto = new VxUserDto();
        BeanUtils.copyProperties(user, dto);
        if (user.getIdent() == 0) {
            dto.setPartnerName("普通用户");
            return dto;
        }
        //查询合伙人类型
        PartnerType partnerType = partnerTypeService.getById(user.getIdent());
        dto.setPartnerName(partnerType.getName());
        return dto;
    }


    //通过分享查询状态详情
    @Override
    public User superInfo(String shareCode) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("share_code", shareCode);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    //更新用户信息
    @Override
    public void update(User user, UpdateWrapper<User> wrapper) {
        userMapper.update(user, wrapper);
    }

    //用户二维码
    @Override
    public CommonResult qrCode(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", user.getOpenId());
        User one = userMapper.selectOne(wrapper);
        if (one.getPhone() == null || one.getPhone() == "") {
            return CommonResult.error(203, "请绑定手机号!");
        }
        String url = "http://vx.szdrkg.com/personal-lading.html?openid=" + user.getOpenId();
        return CommonResult.success(url, "二维码获取成功");
    }

    //修改资料
    @Override
    public void bind(User user) {
        QueryWrapper<BillLading> wrapper = new QueryWrapper<>();
        wrapper.eq("i_phone", user.getPhone());
        List<BillLading> billList = billLadingMapper.selectList(wrapper).stream().limit(1).collect(Collectors.toList());
        Integer superId = null;
        if (billList != null) {
            for (BillLading lading : billList) {
                superId = lading.getSuperId();
                user.toBuilder().superId(superId).build();
            }
        }
        UpdateWrapper<User> update = new UpdateWrapper<>();
        update.eq("open_id", user.getOpenId());
        userMapper.update(user, update);
    }

    /**
     * 绑定银行卡
     *
     * @param user
     */
    @Override
    public void bank(User user) {
        UpdateWrapper<User> update = new UpdateWrapper<>();
        update.eq("open_id", user.getOpenId());
        userMapper.update(user, update);
    }


    @Override
    public CommonResult getIncome(PageVo pageVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", pageVo.getOpenId());
        User vxUser = this.getOne(wrapper);

        QueryWrapper<UserIncome> income = new QueryWrapper<>();
        income.eq("open_id", pageVo.getOpenId());
        List<UserIncome> userIncomeList = userIncomeService.list(income);
        BigDecimal reduce = userIncomeList.stream().map(UserIncome::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

        //本月
        List<UserIncome> maths = userIncomeMapper.maths(pageVo.getOpenId());
        BigDecimal mathBig = maths.stream().map(UserIncome::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        //上月
        List<UserIncome> lastMath = userIncomeMapper.lastMath(pageVo.getOpenId());
        BigDecimal lastMathBig = lastMath.stream().map(UserIncome::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        QueryWrapper<User> sub = new QueryWrapper<>();
        sub.eq("super_id", vxUser.getId());
        List<User> vxUserList = this.list(sub);

        LoanPlanDto dto = new LoanPlanDto();
        dto.setFinalIncome(reduce);
        dto.setPartners(vxUserList.size());
        dto.setMonth(mathBig);
        dto.setLastMonth(lastMathBig);
//        dto.setUserIncomeList(userIncomeList);

        return CommonResult.success(dto);
    }

    @Override
    public PageInfo<UserIncome> getPageListIncome(PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getSize());
        QueryWrapper<UserIncome> income = new QueryWrapper<>();
        income.eq("open_id", pageVo.getOpenId());
        List<UserIncome> userIncomeList = userIncomeService.list(income);
        PageInfo<UserIncome> userIncomePageInfo = new PageInfo<>(userIncomeList, pageVo.getSize());
        return userIncomePageInfo;
    }

    @Override
    public CommonResult getDIncome(TotalVo vo) {
        if (StringUtils.isEmpty(vo.getId())) return CommonResult.failed("id不能为空");
        DataTotal total = dataTotalService.getById(vo.getId());
        UserIncomeDto dto = new UserIncomeDto();

        if (total != null) {
            dto.setLastDay(total.getLastDay());
            dto.setAddRoll(total.getRoll());
            dto.setAddMea(total.getMea());
            dto.setAddPartner(total.getPartner());

//            QueryWrapper<VxUser> wrapper = new QueryWrapper<>();
            List<User> vxUserList = this.list();
            List<User> seniors = vxUserList.stream().filter((User p) -> p.getIdent() == 1)
                    .collect(Collectors.toList());
            List<User> salesman = vxUserList.stream().filter((User p) -> p.getIdent() == 2)
                    .collect(Collectors.toList());
            //所有合伙人
            dto.setAllPartner(seniors.size() + salesman.size());
            //团长
            dto.setSenior(seniors.size());
            //业务员
            dto.setSalesman(salesman.size());

            List<UserRoll> rollList = userRollService.list();
            //所有消费券
            dto.setAllRoll(rollList.size());
            List<LoanPlan> planList = loanPlanService.list();
            //所有测额
            dto.setAllMea(planList.size());

        }
        return CommonResult.success(dto);
    }


    @Override
    public CommonResult getDInfo(PageVo vo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("ident", 1);
        List<User> vxUserList = this.list(wrapper);
        List<UserDto> dtoList = new ArrayList<>();
        for (User vxUser : vxUserList) {
            UserDto dto = new UserDto();
            dto.setAccount(vxUser.getAccount());
            dto.setIdent(vxUser.getIdent());
            dto.setCreateTime(vxUser.getCreateTime());
            //查询下级
            QueryWrapper<User> lower = new QueryWrapper<>();
            lower.eq("super_id", vxUser.getId());
            List<User> lowerList = this.list(lower);
            dto.setLower(lowerList.size());
            if (lowerList.size() != 0) {
                List<LowerDto> lowerDtoList = new ArrayList<>();
                for (User user : lowerList) {
                    LowerDto lowerDto = new LowerDto();
                    lowerDto.setCreateTime(user.getCreateTime());
                    lowerDto.setAccount(user.getAccount());
                    lowerDto.setIdent(user.getIdent());
                    lowerDtoList.add(lowerDto);
                }
                dto.setDtoList(lowerDtoList);
            }
            dtoList.add(dto);
        }


        return CommonResult.success(dtoList);
    }
    @Override
    public void bindUser(User vxUser) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", vxUser.getOpenId());
        User one = this.getOne(wrapper);
        if (one.getPhone() == null) {
            QueryWrapper<User> phone = new QueryWrapper<>();
            phone.eq("phone", vxUser.getPhone());
            User two = this.getOne(phone);
            if (two != null) {
                //todo 电话不为空 合伙人绑定
                two.setOpenId(one.getOpenId());
                this.updateById(two);
                this.removeById(one.getId());
                return;
            }
            //todo 电话为空
            UpdateWrapper<User> update = new UpdateWrapper<>();
            update.eq("open_id", vxUser.getOpenId());
            this.update(vxUser, update);
            return;
        }
        //todo 电话不为空 正常更新
        UpdateWrapper<User> update = new UpdateWrapper<>();
        update.eq("open_id", vxUser.getOpenId());
        this.update(vxUser, update);
    }
}
